<template>
  <div class="tasks-list">
    <div class="header">
      <div class="state">
        <el-select v-model="selectedState" value-key="id">
          <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item" />
        </el-select>

        <el-popover :width="180" trigger="click">
          <template #reference>
            <span class="info">
              您所服务的活动历史以及正在服务中的活动数量，将会成为更多开发者信赖你的重要依据
            </span>
          </template>
        </el-popover>
        <!-- 发布与创建按钮切换 -->
        <el-button
          type="success"
          v-show="checkList.length && selectedState.state == '0'"
          plain
          @click="handlePublishTaskClick"
          >发布任务</el-button
        >
        <el-button type="primary" v-show="!checkList.length" plain @click="handleCreateTaskClick"
          >创建任务</el-button
        >
      </div>
      <template v-if="isEmpty">
        <el-empty description="暂无数据" />
      </template>

      <template v-for="item in tasksList" :key="item.taskId">
        <div class="content">
          <div class="select">
            <el-checkbox
              :value="checkList.includes(item.taskId)"
              @change="handleCheckChange(item.taskId)"
              v-if="selectedState.state == '0'"
            ></el-checkbox>
            <span v-else class="message" @click="handleListItemClick(item.taskId)">
              <img
                v-if="item.haveMessage"
                src="../../assets/img//message.png"
                style="width: 18px"
              />
            </span>
          </div>
          <div
            class="centerContent"
            @click="handleListItemClick(item.taskId)"
            style="cursor: pointer"
          >
            <div class="title">
              <span>{{ item.taskName }}</span>

              <!-- <el-tag type="info">{{ codeToCharacters[item.taskRole] }}</el-tag> -->
              <span class="iconfont" style="margin-left: 20px">
                <el-icon><Coin /></el-icon>
                {{ item.taskScore }}
              </span>
            </div>
          </div>
          <div class="button">
            <el-button
              v-if="selectedState.state == '0' || selectedState.state == '1'"
              type="danger"
              @click="handleDeleteClick(item.taskId, item.taskName)"
              text
              >删除</el-button
            >
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import { ref, watch, computed, markRaw } from 'vue'
import {
  getTasksByProjectId,
  updateTaskDetail,
  deleteTask
} from '@/service/taskdetail/taskdetail.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const props = defineProps({
  project: Object
})
const originaltasksList = ref<Task[]>([])
const tasksList = ref<Task[]>([])
interface Task {
  taskId: string
  taskName: string
  taskScore: number
  taskRole: string
  taskState: string
  haveMessage: Boolean
}

const checkList = ref<string[]>([])
const isEmpty = computed(() => tasksList.value.length === 0)
const selectedState = ref({ id: 0, label: '待发布', state: '0' })
const id = ref('')
// 所有状态的列表
const options = ref([
  { id: 0, label: '待发布', state: '0' },
  { id: 1, label: '招募中', state: '1' },
  { id: 2, label: '实施中', state: '2' },
  { id: 3, label: '已完成', state: '3' }
])
const fetchTasks = async () => {
  if (props.project?.projectId) {
    const response = await getTasksByProjectId(props.project.projectId)
    originaltasksList.value = response.data
    getDataList(selectedState.value.state)
  }
}

watch(
  () => props.project,
  (newVal) => {
    if (newVal && newVal.projectId) {
      id.value = newVal.projectId
      fetchTasks()
    }
  },
  { immediate: true }
)
watch(
  selectedState,
  () => {
    getDataList(selectedState.value.state)
  },
  { deep: true }
)
const getDataList = (state: string) => {
  const filteredTasks = originaltasksList.value.filter((item) => String(item.taskState) === state)
  tasksList.value = filteredTasks
}
//创建任务事件
const handleCreateTaskClick = () => {
  router.push('/main/createtask/' + id.value)
}
// 发布任务的点击事件
const handlePublishTaskClick = async () => {
  try {
    for (const taskId of checkList.value) {
      const taskToUpdate = originaltasksList.value.find((task) => task.taskId === taskId)
      if (taskToUpdate) {
        taskToUpdate.taskState = '1'
        await updateTaskDetail(taskToUpdate)
      }
    }
    checkList.value = []
    ElMessage.success('任务发布成功')
    await fetchTasks()
  } catch (error) {
    ElMessage.error('任务发布失败')
    console.error('Error publishing tasks:', error)
  }
}

// 单个模块详情的点击事件
const handleListItemClick = (taskId: string) => {
  const href = router.resolve({
    path: '/taskdetail/' + taskId
  })
  // 设置在新页面打开
  window.open(href.href)
}
// 删除任务的点击事件
const handleDeleteClick = (taskId: string, taskName: string) => {
  ElMessageBox.confirm(`确定继续删除"${taskName}"任务吗?`, 'Warning', {
    type: 'warning',
    icon: markRaw(Delete)
  })
    .then(async () => {
      try {
        console.log(taskId)

        await deleteTask(taskId)
        ElMessage({
          type: 'success',
          message: `删除"${taskName}"任务成功`
        })
        fetchTasks()
      } catch (error) {
        ElMessage({
          type: 'error',
          message: `删除"${taskName}"任务失败: ${error}`
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除任务'
      })
    })
}
const handleCheckChange = (taskId: string) => {
  const index = checkList.value.indexOf(taskId)
  if (index > -1) {
    // 如果已经在列表中，移除它
    checkList.value.splice(index, 1)
  } else {
    // 如果不在列表中，添加它
    checkList.value.push(taskId)
  }
  console.log('checkList:', checkList.value)
}

//消息跳转
if (route.query.options) {
  selectedState.value = options.value[route.query.options]
}
</script>

<style lang="less" scoped>
.tasks-list {
  .state {
    padding-bottom: 20px;
    border-bottom: 2px solid #eff2f7;
    .el-select {
      width: 100px;
    }
    .info {
      font-size: 14px;
      margin-left: 30px;
      cursor: pointer;
    }
    .el-button {
      margin-left: 50px;
    }
  }
  .content {
    width: 750px;
    height: 80px;
    box-sizing: border-box;
    padding-top: 9px;
    padding-bottom: 9px;
    margin-left: 20px;
    display: flex;
    justify-content: space-between;
    border-bottom: 2px solid #eff2f7;
    .select {
      padding-left: 10px;
      display: flex;
      align-items: center;
      .message {
        cursor: pointer;
      }
    }
    .centerContent {
      width: 520px;
      height: 80px;
      .title {
        margin-top: 20px;
        font-size: 16px;
        .iconfont {
          color: #f74882;
        }
        .el-tag {
          margin: 0 10px;
        }
      }
      .centerInfo {
        margin: 8px 0;
        span {
          font-size: 14px;
          margin-right: 40px;
        }
      }
      .bottomInfo {
        span {
          font-size: 12px;
          color: #8796a8;
          margin-right: 20px;
        }
      }
    }
    .button {
      margin-top: 15px;
      margin-right: 30px;
    }
  }
  .content:hover {
    background-color: #f4f4f5;
  }
}
</style>
